<template>
	<view class="u-m-40 u-m-t-50">
		<view class="u-flex u-col-center u-font-30 u-m-b-35" style="font-weight: bold;" v-if="form.createTime">
			<u-badge :isDot="true" type="primary"></u-badge>
			<view class="u-m-l-10">{{ form.createTime }}</view>
			<view class="u-m-l-10 u-font-24" style="color: gray;">{{ getDayOfWeek(form.createTime) }}</view>
		</view>
		<view class="top shadow-project">
					
			<view class="task-info">
				<block v-if="form.status == 0">
					<u-icon name="warning" color="#fff" size="30"></u-icon>
					<text class="txt u-m-t-10">待审批</text>
				</block>
				<block v-else-if="form.status == 1">
					<u-icon name="clock" color="#fff" size="30"></u-icon>
					<text class="txt u-m-t-10">已审批，待来访</text>
				</block>
				<block v-else-if="form.status == 2">
					<u-icon name="close-circle" color="#fff" size="30"></u-icon>
					<text class="txt u-m-t-10">审批未通过</text>
				</block>
				<block v-else-if="form.status == 9">
					<u-icon name="checkmark-circle" color="#fff" size="30"></u-icon>
					<text class="txt u-m-t-10">已来访</text>
				</block>
			</view>

			<view class="steps">
				<view class="item">
					<view class="status">
						<u-icon v-if="form.status >= 0" class="check status" name="checkmark-circle-fill" color="#39b54a" size="22"></u-icon>
						<text v-else class="status num">1</text>
					</view>
					<view class="txt">待审批</view>
				</view>
				<view class="item" v-if="form.status != 2">
					<view class="status">
						<u-icon v-if="form.status >= 1" class="check status" name="checkmark-circle-fill" color="#39b54a" size="22"></u-icon>
						<text v-else class="status num">2</text>
					</view>
					<view class="txt">已审批</view>
				</view>
				<view class="item" v-if="form.status == 2">
					<view class="status">
						<u-icon class="check status" name="close-circle-fill" color="#e54d42" size="22"></u-icon>
					</view>
					<view class="txt">审批未通过</view>
				</view>
				<view class="item">
					<view class="status">
						<u-icon v-if="form.status == 9" class="check status" name="checkmark-circle-fill" color="#39b54a" size="22"></u-icon>
						<text v-else class="status num">3</text>
					</view>
					<view class="txt">已来访</view>
				</view>
			</view>

			<view class="qr" v-if="form.status == 1">
				<view class="line">
					<text class="text-bold">通行码</text>  
				</view>
				<view class="item">
					<image :show-menu-by-longpress="true" :src="qrImageData" class="loading" />
				</view>
				<view class="line">
					<!-- <text class="u-font-24 text-grey"> (向工作人员出示进行核验)</text> -->
					<text class="u-font-24 text-grey"> (出示该二维码给门禁设备进行核验)</text>
				</view>
			</view>
		</view>
		<view class="article-box">
			<view class="form-box card-project shadow-project  margin-top">
				<view class="line">填报信息</view>
				<view class="form-main" style="padding: 0;">
					<u-form labelPosition="left" :model="form" :rules="rules" ref="uForm" :errorType="['message']">
						<view class="form-box" style="border-radius: 0">
							<u-form-item label="来访开始日期" label-width="200rpx" prop="lfTime" required>
								<view class="u-flex select-box" @click="dateShow = true">
									<u-input class="u-flex-1 form-input" placeholder="请选择申请来访开始日期" v-model="form.lfTime" readonly />
								</view>
								<u-datetime-picker ref="datetimePicker" :show="dateShow" mode="datetime" :formatter="formatter"
									:minDate="new Date().getTime()" :maxDate="new Date().getTime() + 2592000000"
									@cancel="dateShow = false" @close="dateShow = false" @confirm="onConfirmType" closeOnClickOverlay></u-datetime-picker>
							</u-form-item>
							<u-form-item label="来访结束日期" label-width="200rpx" prop="visitTimeEnd" required>
								<view class="u-flex select-box" @click="dateShow1 = true">
									<u-input class="u-flex-1 form-input" placeholder="请选择申请来访结束日期" v-model="form.visitTimeEnd" readonly />
								</view>
								<u-datetime-picker ref="datetimePicker" :show="dateShow1" mode="datetime" :formatter="formatter"
									:minDate="new Date().getTime()" :maxDate="new Date().getTime() + 2592000000"
									@cancel="dateShow1 = false" @close="dateShow1 = false" @confirm="onConfirmType1" closeOnClickOverlay></u-datetime-picker>
							</u-form-item>
							<u-form-item label="申请人" label-width="110rpx" prop="userName" required>
								<u-input class="form-input" v-model="form.userName" placeholder="请输入申请人" />
							</u-form-item>
							<u-form-item label="申请人电话" label-width="170rpx" prop="userPhone" required>
								<u-input class="form-input" v-model="form.userPhone" placeholder="请输入申请人电话" />
							</u-form-item>
							<u-form-item label="拜访部门" label-width="140rpx" prop="bfDeptName" required>
								<view class="u-flex select-box" @click="deptShow = true">
									<u-input class="u-flex-1 form-input"
										placeholder="请选择拜访部门" v-model="form.bfDeptName" readonly />
								</view>
								<!-- <u-picker title="选择要拜访的部门" :show="deptShow" :columns="deptList" keyName="deptName"
									@cancel="deptShow = false" @close="deptShow = false" @confirm="onConfirmDept" closeOnClickOverlay></u-picker> -->
							</u-form-item>
							<u-form-item label="被访人" label-width="110rpx" prop="bfUserName" required>
								<u-input class="form-input" v-model="form.bfUserName" placeholder="请输入被访人" />
							</u-form-item>
							<u-form-item label="来访人数" label-width="140rpx" prop="lfRs" required>
								<u-input class="form-input" v-model="form.lfRs" placeholder="请输入来访人数" />
							</u-form-item>
							<u-form-item label="来访事由" label-width="140rpx" prop="lfSy" required>
								<u-textarea v-model="form.lfSy" placeholder="请输入来访事由" count autoHeight maxlength="60" disableDefaultPadding />
							</u-form-item>
							<u-form-item label="访客车牌" label-width="140rpx" prop="fkCl">
								<car-number-input @numberInputResult="numberInputResult" :defaultStr="form.fkCl"></car-number-input>
							</u-form-item>
							<u-form-item label="访客人脸" label-width="140rpx" prop="fkRl">
								<u-upload :fileList="form.fkRl" @afterRead="afterRead" @delete="deletePic" name="fkRl" multiple
									:maxCount="1"></u-upload>
							</u-form-item>
							<u-form-item label="相关图片" label-width="140rpx" prop="xgTp">
								<u-upload :fileList="form.xgTp" @afterRead="afterRead" @delete="deletePic" name="xgTp" multiple
									:maxCount="9"></u-upload>
							</u-form-item>
							<u-form-item label="其他补充" label-width="140rpx" prop="qtBc">
								<u-textarea class="form-input" v-model="form.qtBc" count autoHeight maxlength="60" placeholder="请输入其他补充" disableDefaultPadding />
							</u-form-item>
						</view>
					</u-form>
				</view>
			</view>
		</view>
		<view v-if="form.status === 0" class="u-margin-top-30" @click="submitAction">
			<animate-button ref="animeBtn" btn-text="提交"></animate-button>
		</view>
		<u-gap height="100"></u-gap>
		<u-toast ref="uToast"></u-toast>
		<well-treeSelect
			@doConfirm="doConfirmCategorys"
			:showDialog.sync="deptShow"
			:data="deptList"
			:title-text="'选择要拜访的公司部门'"
			:max-selected="1"
			:selectedValues="selectedDeptValues"
			v-if="deptList.length != 0">
		</well-treeSelect>
	</view>
</template>

<script>
	import qrcodeLib from '@/utils/qrcode_lib.js'
	export default {
		data() {
			return {
				id: 0,
				qrImageData: '',
				
				form: {
					lfTime: '', // 申请时间段
					visitTimeEnd: '', // 申请时间段
					userName: '', // 申请人
					userPhone: '', // 申请人电话
					bfDept: 0, // 拜访部门
					bfDeptName: '', // 拜访部门
					bfUserName: '', // 被访人
					fkCl: '', // 访客车牌
					fkRl: [], // 访客人脸
					lfRs: 1,
					lfSy: '', // 来访事由
					qtBc: '', // 其他补充
					xgTp: [], // 相关图片
				},
				rules: {
					lfTime: {
						type: 'string',
						required: true,
						message: '请选择申请来访开始日期',
						trigger: ['blur', 'change']
					},
					visitTimeEnd: {
						type: 'string',
						required: true,
						message: '请选择申请来访结束日期',
						trigger: ['blur', 'change']
					},
					userName: {
						type: 'string',
						required: true,
						message: '请输入申请人',
						trigger: ['blur', 'change']
					},
					userPhone: {
						type: 'string',
						required: true,
						message: '请输入申请人电话',
						trigger: ['blur', 'change']
					},
					bfDeptName: {
						type: 'string',
						required: true,
						message: '请选择拜访部门',
						trigger: ['blur', 'change']
					},
					bfUserName: {
						type: 'string',
						required: true,
						message: '请输入拜访人',
						trigger: ['blur', 'change']
					},
					// fkCl: {
					// 	type: 'string',
					// 	required: true,
					// 	message: '请输入访客车牌',
					// 	trigger: ['blur', 'change']
					// },
					// fkRl: {
					// 	type: 'string',
					// 	required: true,
					// 	message: '请输入访客人脸',
					// 	trigger: ['blur', 'change']
					// },
					lfRs: {
						type: 'number',
						required: true,
						message: '请输入来访人数',
						trigger: ['blur', 'change']
					},
					lfSy: {
						type: 'string',
						required: true,
						message: '请输入来访事由',
						trigger: ['blur', 'change']
					},
					// xgbc: {
					// 	type: 'string',
					// 	required: true,
					// 	message: '请输入其他补充',
					// 	trigger: ['blur', 'change']
					// },
					// xgtp: {
					// 	type: 'array',
					// 	required: true,
					// 	message: '请上传相关图片',
					// 	trigger: ['blur', 'change']
					// },
				},
				
				dateShow: false,
				dateShow1: false,
				deptShow: false,
				deptList: [
					// [
					// 	{
					// 		id: 1,
					// 		value: '生产部'
					// 	},
					// 	{
					// 		id: 2,
					// 		value: '技术部'
					// 	},
					// 	{
					// 		id: 3,
					// 		value: '行政部'
					// 	}
					// ]
				],
				selectedDeptValues: [],
			}
		},
		computed: {
			deptInfo() {
				if (Object.keys(this.$store.state.deptInfo).length != 0) {
					return this.$store.state.deptInfo
				} else if (Object.keys(uni.getStorageSync('deptInfo')).length != 0) {
					return uni.getStorageSync('deptInfo')
				} else {
					return []
				}
			},
		},
		onLoad() {
			const {
				id
			} = this.$Route.query;
			this.id = id;
			// this.deptList = [this.deptInfo];
			this.getInfo();
		},
		methods: {
			getInfo() {
				this.$api.getInfoVisit(this.id).then(res => {
					let d = res.data;
					this.id = d.id;
					this.form = Object.assign({}, d, {
						fkRl: d.fkRl ? d.fkRl.split(",").map((v) => ({ url: v })) : [], // 访客人脸
						xgTp: d.xgTp ? d.xgTp.split(",").map((v) => ({ url: v })) : [], // 相关图片
					})
					// this.form = {
					// 	lfTime: d.lfTime, // 申请时间段
					// 	userName: d.userName, // 申请人
					// 	userPhone: d.userPhone, // 申请人电话
					// 	bfDept: d.bfDept, // 拜访部门
					// 	bfDeptName: d.bfDeptName, // 拜访部门
					// 	bfUserName: d.bfUserName, // 被访人
					// 	fkCl: d.fkCl, // 访客车牌
					// 	fkRl: d.fkRl ? d.fkRl.split(",").map((v) => ({ url: v })) : [], // 访客人脸
					// 	lfSy: d.lfSy, // 来访事由
					// 	lfRs: d.lfRs, // 来访人数
					// 	qtBc: d.qtBc, // 其他补充
					// 	xgTp: d.xgTp ? d.xgTp.split(",").map((v) => ({ url: v })) : [], // 相关图片
					// }
					this.selectedDeptValues = [this.form.bfDept]
					this.deptList = this.arrayToTree(this.deptInfo)
					this.qrImageData = qrcodeLib.drawImg(d.qrCode, {
						typeNumber: 1,
						errorCorrectLevel: 'L',
						size: 450
					});
				})
			},
			formatter(type, value) {
				if (type === 'year') {
					return `${value}年`
				}
				if (type === 'month') {
					return `${value}月`
				}
				if (type === 'day') {
					return `${value}日`
				}
				if (type === 'hour') {
					return `${value}时`
				}
				if (type === 'minute') {
					return `${value}分`
				}
				return value
			},
			onConfirmType(item) {
				this.form.lfTime = uni.$u.timeFormat(item.value, 'yyyy-mm-dd hh:MM');
				this.dateShow = false;
			},
			onConfirmType1(item) {
				this.form.visitTimeEnd = uni.$u.timeFormat(item.value, 'yyyy-mm-dd hh:MM');
				this.dateShow1 = false;
			},
			onConfirmDept(item) {
				this.form.bfDept = item.value[0].id;
				this.form.bfDeptName = item.value[0].deptName;
				this.deptShow = false;
				this.$refs.uForm.validateField('bfDeptName');
			},
			submitAction() {
				if (this.$refs.animeBtn.status != 1) return
				this.$refs.uForm.validate().then(res => {
					this.$refs.animeBtn.loading()
					let fkRl = [], xgTp = [];
					for (let i in this.form.fkRl) {
						fkRl.push(this.form.fkRl[i].url)
					}
					for (let i in this.form.xgTp) {
						xgTp.push(this.form.xgTp[i].url)
					}
					this.$api.editVisit({
						...this.form,
						id: this.id,
						lfTime: this.form.lfTime + ':00',
						visitTimeEnd: this.form.visitTimeEnd + ':00',
						fkRl: fkRl.join(','),
						xgTp: xgTp.join(',')
					}).then(res => {
						this.$refs.animeBtn.success()
						this.$refs.uToast.show({
							message: '修改成功',
							type: 'success',
							duration: 1500,
							complete: () => {
								this.$fallback(1, {
									key: 'reset',
									back: true
								})
							}
						});
					}).catch(() => {
						this.$refs.animeBtn.fail()
						setTimeout(() => {
							this.$refs.animeBtn.reset()
						}, 3000)
					})
				}).catch(errors => {
					uni.$u.toast('校验失败')
				});
			},
			
			// 删除图片
			deletePic(event) {
				this.form[event.name].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this.form[event.name].length
				lists.map((item) => {
					this.form[event.name].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this.form[event.name][fileListLen]
					this.form[event.name].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
				this.$refs.uForm.validateField(event.name);
			},
			uploadFilePromise(path) {
				return new Promise((resolve, reject) => {
					this.$upload.PhotoOrVideo((url, index, type) => {
						uni.showToast({
							title: '上传成功！'
						});
						resolve(url);
					}, {
						path
					})
				})
			},
			numberInputResult(e) {
				this.form['fkCl'] = e;
				this.$refs.uForm.validateField('fkCl');
			},
			getDayOfWeek(date) {
			  const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
			  const dayIndex = new Date(date).getDay();
			  return days[dayIndex];
			},
			
			doConfirmCategorys(selectedItems) {
				this.form.bfDept = selectedItems[0].value;
				this.form.bfDeptName = selectedItems[0].label;
				this.$refs.uForm.validateField('bfDeptName');
			},
			
			arrayToTree(items) {
			  const result = [];   // 存放结果集
			  const itemMap = {};  // 
			  for (const item of items) {
			    const id = item.id;
			    const pid = item.parentId;
			
			    if (!itemMap[id]) {
			      itemMap[id] = {
			        children: [],
			      }
			    }
			
			    itemMap[id] = {
			      ...item,
			      children: itemMap[id]['children'],
				  label: item.deptName,
				  value: item.id,
			    }
			
			    const treeItem =  itemMap[id];
			
			    if (pid === 0) {
			      result.push(treeItem);
			    } else {
			      if (!itemMap[pid]) {
			        itemMap[pid] = {
			          children: [],
			        }
			      }
			      itemMap[pid].children.push(treeItem)
			    }
			
			  }
			  return result;
			}
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules);
			this.$refs.datetimePicker.setFormatter(this.formatter)
		}
		
	}
</script>

<style lang="scss" scoped>
	.select-box {
		width: 100%;
	}
	.text-grey {
		color: #8799a3!important;
	}
	
	.text-bold {
		font-weight: bold!important;
	}
	
	image.loading::before {
		content: "";
		background-color: #f5f5f5;
		display: block;
		position: absolute;
		width: 100%;
		height: 100%;
		z-index: -2;
	}
	
	image.loading::after {
		content: "\e7f1";
		font-family: "icon";
		position: absolute;
		top: 0;
		left: 0;
		width: 32rpx;
		height: 32rpx;
		line-height: 32rpx;
		right: 0;
		bottom: 0;
		z-index: -1;
		font-size: 32rpx;
		margin: auto;
		color: #ccc;
		-webkit-animation: icon-spin 2s infinite linear;
		animation: icon-spin 2s infinite linear;
		display: block;
	}

	.top {
		width: 100%;
		border-radius: 20rpx !important;
	} 
	
	.top .task-info {
		width: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		color: #fff;
		background-image: linear-gradient(45deg, #24a9eb, #106ad8);
		height: 200rpx;
	}
	
	.top .task-info .icn {
		font-size: 60rpx;
	}
	
	.top .task-info .txt {
		font-size: 30rpx;
	}
	
	
	.top .steps {
		width: 100%;
		display: flex;
		background-color: #fff;
		padding: 30rpx 0;
	}
	
	.top .steps .item {
		flex: 1;
		text-align: center;
		min-width: 100rpx;
		display: flex;
		flex-direction: column;
		position: relative;
	}
	
	.top .steps .item .status {
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
		height: 70rpx;
	}
	
	.top .steps .item .status .check {
		font-size: 45rpx;
		color: #106ad8;
	}
	
	.top .steps .item .status .num {
		width: 36rpx;
		height: 36rpx;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 22rpx;
		border: 2rpx solid #999;
		color: #999;
	}
	
	.top .steps .item>.txt {
		font-size: 26rpx;
		color: #999;
	}
	
	.top .steps .item::before,
	.top .steps .item::after {
		content: "";
		display: block;
		position: absolute;
		height: 0px;
		width: calc(100% - 80rpx);
		border-bottom: 1rpx solid #ccc;
		left: calc(0rpx - (100% - 80rpx) / 2);
		top: 30rpx;
		z-index: 0;
	}
	
	.top .steps .item:first-child::before,
	.top .steps .item:first-child::after {
		display: none;
	}
	
	.top .qr {
		width: 100%;
		display: flex;
		flex-direction: column;
	}
	
	.top .qr {
		width: 100%;
		display: flex;
		flex-direction: column;
		padding: 30rpx 0;
		background-color: #fff;
	}
	
	.top .qr .line {
		width: 100%;
		text-align: center;
		padding: 20rpx 0;
	}
	
	.top .qr .item {
		width: 100%;
		display: flex;
		justify-content: center;
		align-items: center;
	}
	
	.top .qr .item image {
		width: 450rpx;
		height: 450rpx;
	}
	
	.article-box .line {
		width: 100%;
		text-align: center;
		padding: 30rpx 0;
		background-color: #fff;
		color: #666;
		border-bottom: 2rpx dashed #ccc;
	}
	
	.form-box .flow {
		width: 100%;
		padding: 20rpx 40rpx;
		font-size: 24rpx;
		border-bottom: 2rpx dashed #eee;
		color: #666;
	}
	
	.form-box .time {
		color: #999;
	}
	
	.form-box .flow:last-child {
		border-bottom: 0rpx dashed #fff;
	}
	
	.form-box .flow .img {
		width: 100%;
		display: flex;
		flex-wrap: wrap;
		padding-top: 20rpx;
	}
	
	.form-box .flow .img image {
		width: 110rpx;
		height: 110rpx;
		border-radius: 5rpx;
		margin-right: 10rpx;
		margin-bottom: 10rpx;
	}
</style>